<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Article;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;



class ArticlesController extends Controller
{
    public function index(){
        $articles = Article::latest() -> published() -> get();
        return view('articles.index', compact('articles'));
    }

    public function show(Request $request,$id){
        $article = Article::findOrFail($id);
        //友好时间
        // dd($article -> published_at -> diffForHumans());
        return view('articles.show', compact('article'));

    }

    public function create(){
        return view('articles.create');
    }

    public function store(Request $request){
   
        $input = $request -> all();
        $input['published_at'] = Carbon::now();

        // $validator = Validator::make($input, [
        //     'title' => 'required|max:6',
        //     'content' => 'required'
        // ]);

        // if ($validator -> fails()) {
        //     return redirect('/articles/create') -> withInput() -> withErrors($validator);
        // }

        $this -> validate($request, ['title' => 'required', 'content' => 'required']);
        
        //一对多关系 array_merge(['user_id' => \Auth::user()->id, $input])
        Article::create(array_merge(['user_id' => \Auth::user()->id], $input));

        return redirect('/articles');
  
    }

    public function edit($id){
        $article = Article::findOrFail($id);
 
        return view('articles.edit', compact('article'));
    }

    public function update(Request $request, $id){
        $this -> validate($request, ['title' => 'required', 'content' => 'required']);
        $article = Article::findOrFail($id);
      
        $article ->update($request ->all());

        return redirect('/articles');

    }




}
